package com.orhon.smartcampus.modules.user.controller;
import java.io.*;
import java.util.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.DictionaryDao;
import com.orhon.smartcampus.modules.base.entity.Dictionary;
import com.orhon.smartcampus.utils.TeacherExcelUtil;
import com.orhon.smartcampus.utils.Util;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.opc.internal.ContentType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.teacher.dao.TInformationDao;
import com.orhon.smartcampus.modules.teacher.entity.TInformation;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.modules.user.dao.UsersDao;
import com.orhon.smartcampus.modules.user.entity.Users;
import com.orhon.smartcampus.utils.ExcelUtil;
import com.orhon.smartcampus.utils.R;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@RestController
@RequestMapping(value = "/export", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TeacherElxeController<E> {

	@Autowired
	private TokenService tokenService;

	@Autowired
	HibernateTemplate hibernateTemplate;

	@Autowired
	private UsersDao usersDao;

	@Autowired
	DictionaryDao dictionaryDao;

	@Autowired
	private TInformationDao informationDao;

	@Autowired
	private SchoolsDao schoolsDao;

	@Autowired
	private TInformationDao tInformationDao;

	/**
	 * 导出模板
	 *
	 * @return
	 */
	@GetMapping(value = "/exportTecher")
	public void export(HttpServletResponse response, @RequestParam HashMap<String, Object> maps) throws Exception {
		//String[] headers =  ((String) maps.get("headers")).split(",");
		//String[] eclass =  ((String) maps.get("eclass")).split(",");
		try {
			ServletOutputStream out = response.getOutputStream();	
			/*HashMap<String,Object> dictionaryList = dictionaryService.getDictionaryList("student_options");
			ArrayList<String> arrayList = new ArrayList<String>();
			ArrayList<String> array = new ArrayList<String>();
			for (String string : headers) {
				if(string.equals("student_name")) {
					arrayList.add(JSON.parseObject(dictionaryList.get(string).toString()).get("zh").toString());
					arrayList.add(JSON.parseObject(dictionaryList.get(string).toString()).get("zh").toString()+"(蒙文)");
					array.add(string);
					array.add(string+"_mn");
				}else {
					array.add(string);
					arrayList.add(JSON.parseObject(dictionaryList.get(string).toString()).get("zh").toString());
				}
			}*/
			TeacherExcelUtil eeu = new TeacherExcelUtil();
			HSSFWorkbook workbook = new HSSFWorkbook();
			ArrayList<String> arrayList = new ArrayList<String>();
			ArrayList<String> array = new ArrayList<String>();
			arrayList.add("教职工名称");
			arrayList.add("性别");
			arrayList.add("民族");
			arrayList.add("身份证号");
			arrayList.add("联系方式");
			arrayList.add("出生年月日");

			//arrayList.add("教师蒙文名");
			//arrayList.add("教师英文名");
			//arrayList.add("教师身份证号码");
			//arrayList.add("教师性别(男:gender_1,女:gender_2)");
			//arrayList.add("民族");
		/*	arrayList.add("联系方式");
			arrayList.add("年级");
			arrayList.add("学科");
			arrayList.add("学段");
			arrayList.add("在岗状态");
			arrayList.add("最高职称");
			arrayList.add("政治面貌");*/
			List<List<String>> data = new ArrayList<List<String>>();
			List<String> list = new ArrayList<>();
			System.out.println("总数:" + list.size());

			data.add(list);
			String[] array1 = arrayList.toArray(new String[arrayList.size()]);
			String[] array2 = array.toArray(new String[array.size()]);
			int i = 0;
			eeu.exportExcel(workbook, i, "教师详情表", array1, array2, data, out, "教师基础信息表");
			//			for (String string : eclass) {
			//				eeu.exportExcel(workbook, i,string , array1,array2, data, out,string);
			//				i++;
			//			}
			//原理就是将所有的数据一起写入，然后再关闭输入流。
			setResponseHeader(response, "教师导入模板.xls");
			workbook.write(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//发送响应流方法
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}


	/**
	 * 导入
	 *
	 * //@param request
	 * //@param model
	 * @return
	 * @throws Exception
	 * @throws FileNotFoundException
	 */
	@CrossOrigin(origins = {"http://localhost:4200", "null","http://smartdevpccn.orhoncloud.com","http://www.edu.mongol.pub"})
	//@CrossOrigin(origins = {"*", "null"})
	@PostMapping(value = "/teacher")
	//@Transactional(readOnly = false)

	public R xlsx(@RequestParam(required = false) MultipartFile file) throws Exception {
				  //@RequestBody byte[] bytesFile
		//InputStream inputStream = new ByteArrayInputStream(bytesFile);
		//MultipartFile file1 = new MockMultipartFile("", inputStream);
		if (file.isEmpty() != true) {
			String token = tokenService.getSystemToken();
			//String token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsic3ByaW5nLWJvb3QtYXBwbGljYXRpb24iXSwidXNlcl90eXBlIjoiYWRtaW4iLCJzY2hvb2xfaWQiOjUzNSwidXNlcl9uYW1lIjoib3Job24yIiwic2NvcGUiOlsic21hcnRjYW1wdXMtYmFzZSJdLCJleHAiOjE1NzU5MTk5NjIsInVzZXJpZCI6MTcxMDEsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiI4Y2RmMmFlZC05ODMzLTQ4YTktYTEwYi04NGI1M2Y4ZDY1ODYiLCJjbGllbnRfaWQiOiJiYXNlIiwidXNlcm5hbWUiOiJvcmhvbjIifQ.Wn99r70jIAQvYw8UZHQqNQ3wbp67Vcb9bZwBMyQfKaM";
			Long school_id = JwtUtils.getSchoolId(token);
			Schools schools = schoolsDao.findById(school_id);
			if (schools == null) {
				return R.error();
			}
			InputStream stream = file.getInputStream();
			try {
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(stream);
				// 循环工作表Sheet         
				for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
					HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
					if (hssfSheet == null) {
						continue;
					}
					/*HSSFRow hssfRow = hssfSheet.getRow(1);
					ArrayList<String> list = new ArrayList<String>();
					int j = 0;
					for (Cell cell : hssfRow) {
						String value = getValue(hssfRow.getCell(j));
						list.add(value);
						j++;
					}*/
					// 循环行Row
					for (int rowNum = 3; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
						HSSFRow hssfRow1 = hssfSheet.getRow(rowNum);
						if (hssfRow1 != null) {
							//Users users = new Users();
							//users.setIdCard(getValue(hssfRow1.getCell(1)));
							//users.setUsername(getValue(hssfRow1.getCell(1)));
							//users.setPassword("$2y$10$fe8uwZzf6Qdr5rX9WQ7NauLjQz6Fn5EBuMH60720aomWCvxtDx7ii");
							//users.setSchool(schools);
							//users.setUser_type("student");
							try {
								//	usersDao.add(users);
								TInformation information = new TInformation();
								JSONObject object = new JSONObject();
								object.put("en","");
								object.put("mn","");
								object.put("zh", getValue(hssfRow1.getCell(0)));

								String gender = null;
								if (hssfRow1.getCell(1) != null) {
									String cell = getValue(hssfRow1.getCell(1));
									String hql = "from Dictionary where deleted_at = null and dictionary_name " + Util.decide("like_" + cell);
									List<Dictionary> dictionaries = dictionaryDao.find(hql, null);
									if (dictionaries != null && dictionaries.size() > 0) {
										gender = dictionaries.get(0).getDictionaryValue();
									}
								}
								String nation = null;
								if(hssfRow1.getCell(2) != null){
									String cell = getValue(hssfRow1.getCell(2));
									String hql = "from Dictionary where deleted_at = null and dictionary_name " + Util.decide("like_" + cell);
									List<Dictionary> dictionaries = dictionaryDao.find(hql, null);
									if (dictionaries != null && dictionaries.size() > 0) {
										nation = dictionaries.get(0).getDictionaryValue();
									}
								}
								if (hssfRow1.getCell(3) != null) {
									String idCard = getValue(hssfRow1.getCell(3));
									String hql = "from TInformation where deleted_at = null and idcard " + Util.decide("like_" + idCard);
									List<TInformation> count = informationDao.find(hql, null);
									if(count.size()>0){
									return R.Repeat().put("data","当前身份证号已导入，无需重复导入！");
									}

								}
								information.setGender(gender);
								information.setNation(nation);
								information.setTeacherName(object.toJSONString());
								information.setIdcard(getValue(hssfRow1.getCell(3)));
								information.setCreatedAt(new Date());
								information.setTelnumber(getValue(hssfRow1.getCell(4)));
								information.setBaseSchoolsBySchoolId(schools);
								Long userId = (Long) teacherSaveUser(school_id, information);
								information.setUserUsersByUserId(usersDao.get(Users.class, userId));
								HSSFCell birthday = hssfRow1.getCell(5);
								if("".equals(birthday)){
									information.setBirthday(null);
								}else{
									information.setBirthday(TeacherExcelUtil.importByExcelForDate(birthday));
								}
								tInformationDao.saveOrUpdate(information);
							} catch (Exception e) {
								R.error();
							}
						}
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return R.ok().put("data", "导入成功");
		}
		return R.error();
	}

	@SuppressWarnings("static-access")
	private String getValue(HSSFCell hssfCell) {
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			// 返回数值类型的值                 
			return String.valueOf(hssfCell.getNumericCellValue());
		} else {
			// 返回字符串类型的值
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}

	public Object teacherSaveUser(Long schoolId, TInformation tInformation) {
		/**
		 * 是否存在基础用户信息
		 */
		Long userId;
		DetachedCriteria u_criteria = DetachedCriteria.forClass(Users.class);
		u_criteria.add(Restrictions.isNull("deleted_at"));
		u_criteria.add(Restrictions.eq("idCard", tInformation.getIdcard()));
		List<Users> users = (List<Users>) usersDao.findByCriteria(u_criteria);
		Users old_user = users.size() > 0 ? users.get(0) : null;
		if (old_user != null) {
			userId = old_user.getId();
		} else {
			Users user = new Users();
			if (tInformation.getIdcard() != null) {

				user.setIdCard(tInformation.getIdcard());
				user.setUsername(tInformation.getIdcard());
			}
			BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
			String encode = bCryptPasswordEncoder.encode("123456");
			String s = convertJavaBcryptPassword(encode);
			user.setPassword(s);
			if (tInformation.getEmail() != null) {

				user.setEmail(tInformation.getEmail());
			}
			user.setUser_type("teacher");
			Schools schools = schoolsDao.get(Schools.class, schoolId);
			user.setSchool(schools);
			Users new_user;
			try {
				new_user = usersDao.save(user);
			} catch (Exception e) {
				return Result.error(500, "" + e);
			}
			userId = new_user.getId();
		}
		return userId;
	}

	private String convertJavaBcryptPassword(String oldPass) {
		String old_password = oldPass;
		String new_password = "";
		if (old_password.charAt(2) == 'a') {
			StringBuilder strBuilder = new StringBuilder(old_password);
			strBuilder.setCharAt(2, 'y');
			new_password = strBuilder.toString();
			return new_password;
		} else {
			return old_password;
		}
	}



}
